import { Controller, Get, Logger, Post, Req, Res } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { Request, Response } from 'express';
import { Agent } from 'https';
import { defaultAxiosConfig } from 'src/common/utils';
import { ConfigService } from '@nestjs/config';
// const https = require('https');

@Controller('api')
export class WebProxyController {
  baseUrl = ''; //'https://118.31.15.75:18486';
  constructor(private httpService: HttpService, private readonly config: ConfigService) {
    // this.httpService
    // this.httpService.axiosRef.defaults.withCredentials = true;
    // this.httpService.axiosRef.defaults.insecureHTTPParser = true;
    // this.httpService.axiosRef.defaults.httpsAgent = new Agent({ rejectUnauthorized: false });
    // this.httpService.axiosRef.defaults.validateStatus = function (status) {
    //   return true;
    // };
    this.baseUrl = this.config.get('API_HOST');
  }

  @Get('*')
  async getProxy(@Req() req: Request, @Res() res: Response) {
    const headers = { ...req.headers } as Record<string, string>;
    const observeData = this.httpService.get(this.baseUrl + req.originalUrl, {
      headers,
      ...defaultAxiosConfig,
    });
    observeData.subscribe((sub) => {
      for (const key in sub.headers) {
        res.setHeader(key, sub.headers[key]);
      }
      Logger.log(sub.status, req.path);
      res.status(sub.status).send(sub.data);
    });
  }

  @Post('*')
  async postProxy(@Req() req: Request, @Res() res: Response) {
    const headers = { ...req.headers } as Record<string, string>;
    const observeData = await this.httpService.post(this.baseUrl + req.originalUrl, req.body, {
      headers,
      ...defaultAxiosConfig,
    });
    observeData.subscribe((sub) => {
      for (const key in sub.headers) {
        res.setHeader(key, sub.headers[key]);
      }
      res.status(sub.status).send(sub.data);
    });
  }
}
